<?php
namespace app\api\model;
use app\admin\model\publicuse\HerTime;
use Maowenke\PersonalWechatSdk\payment\WecatePayment;

class AllOrder
{
    protected $message = '';
    public function getMessage(){
        return $this->message;
    }

    /**生成订单
     * @param array $data
     * @param array $user
     * @param array $nursing_lang
     * @param array $type
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function create_order(array $data,array $user,array $nursing_lang,array $type){
        if($type['types']==1){
            return $this->shorttermOrder($data,$user,$nursing_lang);
        }elseif($type['types']==2){
            return $this->langOrder($data,$user,$nursing_lang);
        }elseif ($type['types']==4){
            return $this->nannyOrder($data,$user,$nursing_lang);
        }
        $this->message = '订单没有适应本类型';
        return false;
    }

    /**短期护理生成订单
     * @param array $data
     * @param array $user
     * @param array $nursing_lang
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function shorttermOrder(array $data,array $user,array $nursing_lang){
        $newdata = [
            'name'=>$nursing_lang['name'],
            'order_num'=>getOrder($user['id'],'Z'),
            'nursing_lang_id'=>$nursing_lang['id'],
            'cover_pepo_name'=>$data['cover_pepo_name'],
            'cover_pepo_sex'=>$data['cover_pepo_sex'],
            'is_live'=>$data['is_live'],
            'phone'=>$data['phone'],
            'province'=>$data['province'],
            'city'=>$data['city'],
            'area'=>$data['area']??'',
            'address'=>$data['address'],
            'service_time'=>strtotime($data['service_time']),
            'end_time'=>strtotime($data['service_time'])+86400*(intval($data['days'])),
            'days'=>intval($data['days']),
            'uid'=>$user['id'],
            'age'=>$data['age'],
            'pay_state'=>0,
            'is_assessment'=>1,
            'state'=>1,
            'types'=>empty($data['up_id'])?1:2,
            'status'=>1,
//            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $money = 0;
        if($data['is_live']==1){
            $money = $nursing_lang['home_money']*intval($data['days']);
        }else{
            $money = $nursing_lang['no_hoime_money']*intval($data['days']);
        }
        if($money===0){
            $this->message = '计算金额为0元，请联系客服';
            return false;
        }
        $newdata['money'] = $money;
        $newdata['service_money'] = $money;
        $newdata['platform_money'] = 0;
        if(isset($data['id'])&&$data['id']){
            $order = NursingOrder::find($data['id']);
            $bo = $order->save($newdata);
            if(!$bo){
                $this->message = '生成订单失败';
                return false;
            }
        }else{
            $newdata['create_time'] = time();
            $order = NursingOrder::create($newdata);
            if(!$order){
                $this->message = '生成订单失败';
                return false;
            }
        }
        $newdata['id'] = $order->id;
        if(isset($data['up_id'])&&!empty($data['up_id'])&&$data['up_id']!=0){
            $up_nursing_order = NursingOrder::where('id',$data['up_id'])
                ->field('id,staff_people_id')
                ->find();
            if(!empty($up_nursing_order)){
                $order->staff_people_id = $up_nursing_order->getData('staff_people_id');
                $up_nursing_order->renew_id = $newdata['id'];
                $up_nursing_order->is_renew = 1;
                $up_nursing_order->save(['update_time'=>time()]);
            }
        }
        $res =  $this->pay($newdata,$user['openid'],$nursing_lang);
        if($res===false){
            return false;
        }
        $order->state = 1;
        $order->save(['update_time'=>time()]);
        return $res;
    }

    /**长期护理生成订单
     * @param array $data
     * @param array $user
     * @param array $nursing_lang
     * @return array|bool|mixed|string
     * @throws \Exception
     */

    public function langOrder(array $data,array $user,array $nursing_lang){
        $end_time = HerTime::getManyNextMonth(strtotime($data['service_time']),$data['months']);
        $newdata = [
            'name'=>$nursing_lang['name'],
            'order_num'=>getOrder($user['id'],'Z'),
            'nursing_lang_id'=>$nursing_lang['id'],
            'cover_pepo_name'=>$data['cover_pepo_name'],
            'cover_pepo_sex'=>$data['cover_pepo_sex'],
            'is_live'=>$data['is_live'],
            'phone'=>$data['phone'],
            'province'=>$data['province'],
            'city'=>$data['city'],
            'area'=>$data['area']??'',
            'address'=>$data['address'],
            'service_time'=>strtotime($data['service_time']),
            'end_time'=>$end_time,
            'days'=>$nursing_lang['duration']*intval($data['months']),
            'uid'=>$user['id'],
            'age'=>$data['age'],
            'pay_state'=>0,
            'is_assessment'=>1,
            'state'=>1,
            'status'=>1,
            'types'=>empty($data['up_id'])?1:2,
//            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $money = 0;
        if($data['is_live']==1){
            $money = $nursing_lang['home_money']*intval($data['months']);
        }else{
            $money = $nursing_lang['no_hoime_money']*intval($data['months']);
        }
        if($money===0){
            $this->message = '计算金额为0元，请联系客服';
            return false;
        }
        $platform_money = PlatformFee::where('status',1)
            ->where('months',$data['months'])
            ->where('type',1)
            ->findOrEmpty()->toArray();
        $newdata['service_money'] = $money;
        $newdata['platform_money'] = $platform_money['money'];
        $newdata['money'] = $money+$platform_money['money'];
        if(isset($data['id'])&&$data['id']){
            $order = NursingOrder::find($data['id']);
            $bo = $order->save($newdata);
            if(!$bo){
                $this->message = '生成订单失败';
                return false;
            }
        }else{
            $newdata['create_time'] = time();
            $order = NursingOrder::create($newdata);
            if(!$order){
                $this->message = '生成订单失败';
                return false;
            }
        }
        $newdata['id'] = $order->id;
        if(isset($data['up_id'])&&!empty($data['up_id'])&&$data['up_id']!=0){
            $up_nursing_order = NursingOrder::where('id',$data['up_id'])
                ->field('id,staff_people_id')
                ->find();
            if(!empty($up_nursing_order)){
                $order->staff_people_id = $up_nursing_order->getData('staff_people_id');
                $up_nursing_order->renew_id = $newdata['id'];
                $up_nursing_order->is_renew = 1;
                $up_nursing_order->save(['update_time'=>time()]);
            }
        }
        $res =  $this->pay($newdata,$user['openid'],$nursing_lang);
        if($res===false){
            return false;
        }
        $order->state = 1;
        $order->save(['update_time'=>time()]);
        return $res;
    }

    /**保姆生成订单
     * @param array $data
     * @param array $user
     * @param array $nursing_lang
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function nannyOrder(array $data,array $user,array $nursing_lang){
        $end_time = HerTime::getManyNextMonth(strtotime($data['service_time']),$data['months']);
        $newdata = [
            'name'=>$nursing_lang['name'],
            'order_num'=>getOrder($user['id'],'Z'),
            'nursing_lang_id'=>$nursing_lang['id'],
//            'cover_pepo_name'=>$data['cover_pepo_name'],
//            'cover_pepo_sex'=>$data['cover_pepo_sex'],
            'is_live'=>$data['is_live'],
            'phone'=>$data['phone'],
            'province'=>$data['province'],
            'city'=>$data['city'],
            'area'=>$data['area']??'',
            'contact_name'=>$data['contact_name']??'',
            'address'=>$data['address'],
            'service_time'=>strtotime($data['service_time']),
            'end_time'=>$end_time,
            'days'=>$nursing_lang['duration']*intval($data['months']),
            'uid'=>$user['id'],
            'nanny_options'=>'',
            'pay_state'=>0,
            'is_assessment'=>1,
            'types'=>empty($data['up_id'])?1:2,
            'state'=>1,
            'status'=>1,
//            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $money = 0;
        if($data['is_live']==1){
            $money = $nursing_lang['home_money']*intval($data['months']);
        }else{
            $money = $nursing_lang['no_hoime_money']*intval($data['months']);
        }
        if($money===0){
            $this->message = '计算金额为0元，请联系客服';
            return false;
        }
        $platform_money = PlatformFee::where('status',1)
            ->where('months',$data['months'])
            ->where('type',2)
            ->findOrEmpty()->toArray();
        //处理房屋面积选项
        if(isset($data['house_area'])&&$data['house_area']){
            $nanny_options = NannyOptions::where('status',1)
                ->where('id',$data['house_area'])
                ->field('id,name,money,option_type_id')
                ->findOrEmpty()->toArray();
            if(empty($nanny_options)){
                $this->message = '房屋面积选项不存在';
                return false;
            }
//            $money += $nanny_options['money'];
            $nanny_type = OptionType::where('id',$nanny_options['option_type_id'])
                ->field('id,name')
                ->findOrEmpty()->toArray();
            $newdata['nanny_options']  .= $nanny_type['name'].':'.$nanny_options['name'].';';
            $newdata['nanny_options_ids']['house_area'] = $data['house_area'];
        }
        //处理三餐制作
        if(isset($data['three_meals'])&&$data['three_meals']){
            if(!is_array($data['three_meals'])){
                $data['three_meals'] = explode('|',$data['three_meals']);
            }
            $nanny_type = OptionType::where('name','三餐制作')
                ->field('id,name')
                ->findOrEmpty()->toArray();
            $nanny_options = NannyOptions::where('status',1)
                ->where('id','in',$data['three_meals'])
                ->field('id,name,money')
                ->select()->toArray();
            $newdata['nanny_options']  .= $nanny_type['name'].':';
            foreach ($nanny_options as $value){
//                $money += $value['money'];
                $newdata['nanny_options'] .= $value['name'].',';
            }
            $newdata['nanny_options'] = trim($newdata['nanny_options'],',').';';
            $newdata['nanny_options_ids']['three_meals'] = $data['three_meals'];
        }
        //处理用餐人数
        if(isset($data['have_meals'])&&$data['have_meals']){
            $nanny_type = OptionType::where('name','用餐人数')
                ->field('id,name')
                ->findOrEmpty()->toArray();
            $nanny_options = NannyOptions::where('status',1)
                ->where('id',$data['have_meals'])
                ->field('id,name,money')
                ->findOrEmpty()->toArray();
            if(empty($nanny_options)){
                $this->message = '用餐人数选项不存在';
                return false;
            }
//            $money += $nanny_options['money'];
            $newdata['nanny_options'] .= $nanny_type['name'].':'.$nanny_options['name'].';';
            $newdata['nanny_options_ids']['have_meals'] = $data['have_meals'];
        }
        //处理是否接送小孩
        if(isset($data['meet_child'])&&$data['meet_child']){
            $nanny_type = OptionType::where('name','是否接送小孩')
                ->field('id,name')
                ->findOrEmpty()->toArray();
            $nanny_options = NannyOptions::where('status',1)
                ->where('id',$data['meet_child'])
                ->field('id,name,money')
                ->findOrEmpty()->toArray();
            if(empty($nanny_options)){
                $this->message = '用餐人数选项不存在';
                return false;
            }
//            $money += $nanny_options['money'];
            $newdata['nanny_options'] .= $nanny_type['name'].':'.$nanny_options['name'].';';
            $newdata['nanny_options_ids']['meet_child'] = $data['meet_child'];
        }
        $newdata['service_money'] = $money;
        $newdata['platform_money'] = $platform_money['money'];
        $newdata['money'] = $money+$platform_money['money'];
//        echo '<pre>';
//        print_r($newdata);
//        exit;
        if(isset($data['id'])&&$data['id']){
            $order = NursingOrder::find($data['id']);
            $bo = $order->save($newdata);
            if(!$bo){
                $this->message = '生成订单失败';
                return false;
            }
        }else{
            $newdata['create_time'] = time();
            $order = NursingOrder::create($newdata);
            if(!$order){
                $this->message = '生成订单失败';
                return false;
            }
        }
        $newdata['id'] = $order->id;
        if(isset($data['up_id'])&&!empty($data['up_id'])&&$data['up_id']!=0){
            $up_nursing_order = NursingOrder::where('id',$data['up_id'])
                ->field('id,staff_people_id')
                ->find();
            if(!empty($up_nursing_order)){
                $order->staff_people_id = $up_nursing_order->getData('staff_people_id');
                $up_nursing_order->renew_id = $newdata['id'];
                $up_nursing_order->is_renew = 1;
                $up_nursing_order->save(['update_time'=>time()]);
            }
        }
        $res =  $this->pay($newdata,$user['openid'],$nursing_lang);
        if($res===false){
            return false;
        }
        $order->state = 1;
        $order->save(['update_time'=>time()]);
        return $res;
    }

    /**微信支付
     * @param array $order
     * @param $openid
     * @param array $nursing_lang
     * @return array|bool|mixed|string
     * @throws \Exception
     */
    public function pay(array $order,$openid,$nursing_lang=[]){
        if(empty($nursing_lang)){
            $nursing_lang = NursingLang::where('id',$order['nursing_lang_id'])
                ->findOrEmpty()->toArray();
        }
        if($order['pay_state']!=0){
            $this->message = '订单不是待支付状态';
            return false;
        }
        $pay = [
//            'name'=>$order['name'],
            'body'=>'购买'.$nursing_lang['name'].'服务',
            'out_trade_no'=>$order['order_num'],
            'total_fee'=>$order['money'],
            'openid'=>$openid
        ];
        $newdata = [
            'name'=>$order['name'],
            'order_num'=>$order['order_num'],
            'money'=>$order['money'],
            'uid'=>$order['uid'],
            'body'=>$pay['body'],
            'nursing_order_id'=>$order['id'],
            'state'=>0,
            'status'=>1,
            'create_time'=>time(),
            'update_time'=>time(),
        ];
        $wecateconfig = config('wecate');
        $pay_order = PayOrder::create($newdata);
        $wecateconfig['notify_url'] = request()->domain().'/api/callbackhand/wecate/payorder/'.$pay_order->id;
        $obj = new WecatePayment($wecateconfig);
        $res = $obj->create_orders($pay);
        //需要测试
        $res = [
            'appid'=>$wecateconfig['appid'],
            'noncestr'=>'XXXXX',
            'package'=>"Sign=WXPay",
            'partnerid'=>'XXXXXXXXXX',
            'prepayid'=>$wecateconfig['mch_id'],
            'timestamp'=>time(),
            'sign'=>'XXXXXXX',
        ];
        if($res===false){
            $pay_order->state = 3;
            $pay_order->save(['update_time'=>time()]);
            $this->message = $obj->getMessage();
            return false;
        }
        $pay_order->state = 1;
        $pay_order->save(['update_time'=>time()]);
        return $res;
    }

    /**申请退款
     * @param $order_id
     * @param $reason
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refundOrder($order_id,$reason){
        $order = NursingOrder::where('id',$order_id)
            ->find();
//        echo '<pre>';
//        print_r($order->toArray());
//        exit;
        if(empty($order)){
            $this->message = '订单不存在';
            return false;
        }
        if($order->getData('pay_state')!=2){
            $this->message = '订单在进行别的操作';
            return false;
        }
        $pay_order = PayOrder::where('status',1)
            ->where('nursing_order_id',$order_id)
            ->where('order_num',$order->getData('order_num'))
            ->find();
        if(empty($pay_order)){
            $this->message = '订单不存在';
            return false;
        }
        if($pay_order->getData('state')!=2){
            $this->message = '订单在进行别的操作';
            return false;
        }
        $newdata = [
            'name'=>$pay_order->getData('name'),
            'uid'=>$pay_order->getData('uid'),
            'order_num'=>$pay_order->getData('order_num'),
            'money'=>$pay_order->getData('money'),
            'reason'=>$reason,
            'phone'=>$order->getData('phone'),
            'pay_order_id'=>$pay_order->id,
            'create_time'=>time(),
            'update_time'=>time(),
            'status'=>1,
        ];
        $bool = RefundOrder::create($newdata);
        if(!$bool){
            $this->message = '生成退款订单失败';
            return false;
        }
        $pay_order->state = 4;
        $order->pay_state = 4;
        $bool = $pay_order->save(['update_time'=>time()]);
        if(!$bool){
            $this->message = '生成退款订单失败';
            return false;
        }
        $bool = $order->save(['update_time'=>time()]);
        if(!$bool){
            $this->message = '生成退款订单失败';
            return false;
        }
        return true;
    }
}